<?php
/**
 * Created by PhpStorm.
 * User: yu
 * Date: 2017/1/7
 * Time: 下午4:37
 */

namespace Common\Model;


use Think\Image;

class GoodsModel extends BaseModel
{
	protected $pk        = 'gid';
	protected $tableName = 'goods';
	protected $_validate = [
		[ 'gname' , 'require' , '商品名不能为空' , 3 , 3 ] ,
	];

	public function addGoods ()
	{
		//1.数据验证
		//验证商品名
		if(!$this->create()){
			return ['status'=>'error','message'=>$this->getError()];
		}
		//验证商品详情，售后服务
		$goodsDetailModel = new GoodsDetailModel();
		if(!$goodsDetailModel->create()){
			return ['status'=>'error','message'=>$goodsDetailModel->getError()];
		}
		//验证列表图
		if(!isset($_POST['thumb'])){
			return ['status'=>'error','message'=>'列表图必传'];
		}
		//验证商品图册
		if(!isset($_POST['ggPic'])){
			return ['status'=>'error','message'=>'商品图册至少传一张图'];
		}

		//2.添加商品表数据，得到gid
		$_POST[ 'pic' ]  = current( $_POST[ 'thumb' ] );
		$_POST[ 'time' ] = time();
		$_POST[ 'aid' ]  = $_SESSION[ 'admin' ][ 'id' ];

		$re  = $this->store( $_POST );
		$gid = $re[ 'data' ];
		//3.插入商品详情表
		//======缩略图处理 small medium big
		$small  = '';
		$medium = '';
		$big    = '';
		//创建图像资源
		$image = new Image();
		foreach ( $_POST[ 'ggPic' ] as $v ) {
			//打开图片资源
			$image = $image->open('.'.$v);
			$bigPath    = dirname( $v ) . '/thumb_800_800_' . basename( $v );
			$mediumPath = dirname( $v ) . '/thumb_400_400_' . basename( $v );
			$smallPath  = dirname( $v ) . '/thumb_150_150_' . basename( $v );
			$small .= $smallPath . ',';
			$medium .= $mediumPath . ',';
			$big .= $bigPath . ',';
			$image->thumb(800,800)->save('.'.$bigPath);
			$image->thumb(400,400)->save('.'.$mediumPath);
			$image->thumb(150,150)->save('.'.$smallPath);

		}
		$small      = rtrim( $small , ',' );
		$medium     = rtrim( $medium , ',' );
		$big        = rtrim( $big , ',' );
		$detailData = [
			'small'   => $small ,
			'medium'  => $medium ,
			'big'     => $big ,
			'intro'   => I( 'post.intro' ) ,
			'service' => I( 'post.service' ) ,
			'gid'     => $gid,
		];

		$goodsDetailModel->store($detailData);

		//4.插入商品属性表
		//========普通属性添加=====
		foreach ( $_POST[ 'attr' ] as $k => $v ) {
			if ( !$v ) {
				continue;
			}
			$attrData = [
				'gid'     => $gid ,
				'added'   => 0 ,
				'gtvalue' => $v ,
				'taid'    => $k,
			];
			(new GoodsAttrModel())->store($attrData);
		}

		//=========规格添加
		foreach ($_POST['spec'] as $k =>$v){
			foreach ($v as $kk=>$vv){
				$specData=[
					'gid'=>$gid,
					'taid'=>$k,
					'gtvalue'=> $vv,
					'added'=>$_POST['added'][$k][$kk]
				];
				(new GoodsAttrModel())->store($specData);
			}
		}
		return ['status'=>'success','message'=>'商品添加成功'];
	}
}